﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using SPWeiBo.BusinessEntities;
using SPWeiBo.Utilities;
using Microsoft.SharePoint.Utilities;

namespace SPWeiBo.Repositories
{
    internal class WeiBoRepository : IWeiBoRepository
    {
        private SPWeb Web { get; set; }

        private WeiBoRepository(SPWeb web)
        {
            Web = web;
        }

        public IEnumerable<FollowingRelation> ReadFollowingRelationsByFollower(String followerLoginName)
        {
            if (String.IsNullOrEmpty(followerLoginName))
            {
                throw new ArgumentNullException("followerLoginName");
            }

            var list = Web.Lists[Constants.FOLLOWING_RELATION_LIST];
            var query = new SPQuery();
            query.Query = String.Format(
                "<Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"User\">{1}</Value></Eq></Where>", 
                Constants.FollowingRelationFields.Follower.ToString(), 
                followerLoginName);
            var items = list.GetItems(query);

            var result = items.OfType<SPListItem>().Select(item => GenerateFollowingRelationEntityFromListItem(item)).ToList();
            return result;
        }

        private FollowingRelation GenerateFollowingRelationEntityFromListItem(SPListItem item)
        {
            var follower = item.GetFieldValueAsUser(Constants.FollowingRelationFields.Follower.ToString());
            var followed = item.GetFieldValueAsUser(Constants.FollowingRelationFields.Followed.ToString());

            var followingRelation = new FollowingRelation();
            followingRelation.FollowedLoginName = followed.LoginName;
            followingRelation.FollowedName = followed.Name;
            followingRelation.FollowerLoginName = follower.LoginName;
            followingRelation.FollowerName = follower.Name;

            return followingRelation;
        }

        public IEnumerable<WeiBoItem> ReadLatestWeiBoItems(String userLoginName, DateTime afterThisTime, Int32 maxCount)
        {
            //var followings = ReadFollowingRelationsByFollower(userLoginName);

            //if (followings.Count() == 0)
            //{
            //    return new WeiBoItem[] {};
            //}

            //var usersItemsQuery = GenerateUsersWeiBoItemQuery(followings.Select(f => f.Followed));

            //var list = Web.Lists[Constants.WEIBO_LIST];
            //var query = new SPQuery();
            //query.RowLimit = (UInt32)maxCount;
            //query.Query = String.Format(
            //    "<Where><And>{0}<Gt><FieldRef Name=\"Created\" /><Value Type=\"DateTime\" IncludeTimeValue=\"TRUE\">{1}</Value></Gt></And></Where><OrderBy><FieldRef Name=\"ID\" /></OrderBy>",
            //    usersItemsQuery,
            //    SPUtility.CreateISO8601DateTimeFromSystemDateTime(afterThisTime));
            //var items = list.GetItems(query);
            return null;
        }

        private String GenerateUsersWeiBoItemQuery(IEnumerable<SPUser> users)
        {
            var result = "";

            foreach (var user in users)
            {
                if (result.Length != 0)
                {
                    result = String.Format("<And>{0}<Eq><FieldRef Name=\"Author\" /><Value Type=\"User\">{1}</Value></Eq></And>", result, user.LoginName);
                }
                else
                {
                    result = String.Format("<Eq><FieldRef Name=\"Author\" /><Value Type=\"User\">{0}</Value></Eq>", user.LoginName);
                }
            }

            return result;
        }

        public void CreateWeiBoItem(String content, SPUser author)
        {
            Web.AllowUnsafeUpdates = true;
            var list = Web.Lists[Constants.WEIBO_LIST];
            var newItem = list.Items.Add();
            newItem[Constants.WeiBoItemFields.Title.ToString()] = content;
            newItem["Author"] = author;
            newItem["Editor"] = author;
            newItem.SystemUpdate();
            Web.AllowUnsafeUpdates = false;
        }

        public void CreateFollowingRelation(SPUser follower, SPUser follow)
        {
            //Web.AllowUnsafeUpdates = true;
            //var list = Web.Lists[Constants.FOLLOWING_RELATION_LIST];
            //var newItem = list.Items.Add();
            //newItem[Constants.FollowingRelationFields.Follower.ToString()] = follower;
            //newItem[Constants.FollowingRelationFields.Follow.ToString()] = follow;
            //newItem.SystemUpdate();
            //Web.AllowUnsafeUpdates = false;
        }

        public void CreateFollowingRelation(SPUser follower, String followLoginName)
        {
            var follow = Web.AllUsers[followLoginName];
            CreateFollowingRelation(follower, follow);
        }




        public bool CreateWeiBoItem(string content, string authorLoginName)
        {
            throw new NotImplementedException();
        }

        public bool CreateFollowingRelation(string followerLoginName, string followedLoginName)
        {
            throw new NotImplementedException();
        }

        public static IWeiBoRepository GetInstance(SPWeb web)
        {
            if (web == null)
            {
                throw new ArgumentNullException("web");
            }

            return new WeiBoRepository(web);
        }

        public static IWeiBoRepository GetInstance()
        {
            return GetInstance(SPContext.Current.Web);
        }
    }
}
